package com.weimin.web.config;


import com.weimin.mqtt.server.handler.IMqttUserAuthHandler;
import com.weimin.mqtt.server.listener.IMqttSessionListener;
import com.weimin.mqtt.server.management.MqttSessionManager;
import com.weimin.mqtt.server.model.MqttServerConfig;
import com.weimin.mqtt.server.service.MqttServerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServerBeanConfig {


    @Bean("baseMqttServerConfig")
    @ConfigurationProperties(prefix = "mqtt.server")
    public MqttServerConfig createMqttServerConfig(@Autowired(required = false) IMqttSessionListener mqttSessionListener,
                                                   @Autowired(required = false) IMqttUserAuthHandler mqttUserAuthHandler) {
        MqttServerConfig mqttServerConfig = new MqttServerConfig();
        mqttServerConfig.setSessionListener(mqttSessionListener);
        mqttServerConfig.setUserAuthHandler(mqttUserAuthHandler);
        return mqttServerConfig;
    }

    @Bean("baseMqttSessionManager")
    public MqttSessionManager createMqttSessionManager(@Qualifier("baseMqttServerConfig") MqttServerConfig mqttServerConfig) {
        return new MqttSessionManager(mqttServerConfig.getSessionListener());
    }

    @Bean("baseMqttServerService")
    public MqttServerService createMqttServerService(@Qualifier("baseMqttServerConfig") MqttServerConfig mqttServerConfig,
                                                     @Qualifier("baseMqttSessionManager") MqttSessionManager mqttSessionManager) {
        MqttServerService mqttServerService = new MqttServerService();
        mqttServerService.start(mqttServerConfig, mqttSessionManager);
        return mqttServerService;
    }

}
